<?php


namespace app\home\controller\dealer;

use app\home\controller\Base;
use app\home\model\dealer\Dealer;
use app\home\service\UserToken;
use app\home\service\CodeService;
use app\lib\api\LoginOrRegisterFormValidate;

class Login extends Base
{
    protected $model;
    protected $param;
    /**
     * Login constructor.
     * @param Dealer $model
     */
    public function __construct(Dealer $model )
    {
        $this->model = $model;
        $this->param = input('post.');
    }
    /**
     * 用户登录
     * @param int phone 手机号码
     * @param int code  短信验证码(待接入)
     */
    public function userLogin()
    {
        (new LoginOrRegisterFormValidate())->goCheck();
        $userInfo=$this->getUserData();
        if(empty($userInfo)){
            $this->loginRegister();
        };   //未注册
        $token = $this->updateToken($this->createToken(),$this->param['phone']);
        return  $token ? CodeService::Response(200,'登录成功',['token'=>$token]) : CodeService::SERVER_ERROR_TRY_AGAIN_LATER;
    }

    private function createToken()
    {
        $token =UserToken::createToken();
        cookie(md5(config('salt')), $token);
        return $token;
    }

    private function updateToken($token,$phone)
    {
        $this->model->save(['token'=>$token],['phone'=>num_secret($phone)]);
        return $token;
    }

    private function loginRegister()
    {
        $map = [
            'phone' => num_secret($this->param['phone']),
            'nick_name'  =>tel_deal($this->param['phone']),
            'dealer_code' =>randomString(8),
            'create_time' =>date_time()
        ];
        $Dealer=new Dealer();
        return  $Dealer->insert($map);
    }
    public function getUserData(){
        $result = $this->model->where('phone', num_secret($this->param['phone']))->field(['u_id','phone'])->find();
        return $result;
    }

}